import React, { useState } from "react";
import "./app5.scss";
export default function App3() {
const [goitem, goItem] = useState([
{ id: 1, value: 1 },
{ id: 2, value: 2 },
{ id: 3, value: 3 }
]);
const additem = () => {
goItem([
{ id: 4, value: 4 },
{ id: 1, value: 1 },
{ id: 2, value: 2 },
{ id: 3, value: 3 }
]);
};
return (
<div className="div_bg">
<button onClick={additem}>點我</button>
<ul>
{goitem.map((e) => (
<li key={e.id}>{e.value}</li>
))}
</ul>
</div>
);
}
範例:https://codesandbox.io/s/cocky-monad-lip4i
這是一個KEY寫完整的例子,會發現新增一個數據時只有原本不存在的<li>
才會被更新
import React, { useState } from "react";
import "./app5.scss";
export default function App3() {
const [goitem, goItem] = useState([
{ id: 1, value: 1 },
{ id: 2, value: 2 },
{ id: 3, value: 3 }
]);
const additem = () => {
goItem([
{ id: 4, value: 4 },
{ id: 1, value: 1 },
{ id: 2, value: 2 },
{ id: 3, value: 3 }
]);
};
return (
<div className="div_bg">
<button onClick={additem}>點我</button>
<ul>
{goitem.map((e) => (
<li>{e.value}</li>
))}
</ul>
</div>
);
}
會發現點擊後全部的<li>
都被重新渲染,這樣在ui上會很不好,所以key的重要性就在這裡
範例:https://codesandbox.io/s/unruffled-dust-srnfh